$(function(){
    var _path = window.location.href.split('/');
    window._sys = {
        'url' : [_path[_path.length-2], _path[_path.length-1]].join('/'),
        'user' : Api.get('user'),
        'access' : Api.get('access'),
    };
    // no login check
    if(!window._sys['user']){
        $('html').html('No login request, <span id="no-login-return-timer">3</span>s go to <a id="no-login-return" href="/Public/login.html">Login</a>');
        var timer = 3;
        setInterval(function(){
            timer--;
            $('#no-login-return-timer').html(timer);
            if(timer == 0){
                window.location.href = '/Public/login.html';
            }
        }, 1000);
    }else{
        $('#logined-user-name').html(window._sys['user']['name']);
        if(window._sys['user']['default_password'] == 1){
            var changePWDHtml = `<div class="modal fade" id="changeDefaultPWD" aria-labelledby="changeDefaultPWDLabel" role="dialog" tabindex="-1" aria-hidden="true" style="display: none;z-index: 1701;">
                <div class="modal-dialog modal-simple modal-center">
                    <form class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">×</span>
                            </button>
                            <h4 class="modal-title" id="changeDefaultPWDLabel">You're using a default password, please set a password...</h4>
                        </div>
                        <div class="modal-body">
                            <div class="row">
                                <div class="form-group" style="height: 40px; line-height:40px;">
                                    <label class="col-sm-3 control-label">New Password</label>
                                    <div class="col-sm-9">
                                        <input type="text" class="form-control" id="change-dpwd-pwd" name="New Password" value="">
                                    </div>
                                </div>
                                <div class="form-group" style="height: 40px; line-height:40px;">
                                    <label class="col-sm-3 control-label">Password Confirm</label>
                                    <div class="col-sm-9">
                                        <input type="text" class="form-control" id="change-dpwd-pwd-confirm" name="email" value="">
                                    </div>
                                </div>
                                <div class="form-group" style="height: 40px; line-height:40px;">
                                    <button class="btn btn-primary btn-outline" data-dismiss="modal" type="button" id="change-dpwd-submit">Submit</button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <a class="panel-action" data-toggle="modal" id="change-default-password" data-target="#changeDefaultPWD" href="#" aria-expanded="false">Change Default Password</a>
            `;
            $('body').append(changePWDHtml);
            $('#change-default-password').trigger('click');
            $('#change-dpwd-submit').click(function(){
                var pwd = $('#change-dpwd-pwd').val().trim(),
                    cpwd = $('#change-dpwd-pwd-confirm').val().trim();
                if(pwd.length == 0){
                    $.showError('News password can not be empty.', 400);
                    return false;
                }
                if(pwd != cpwd){
                    $.showError('Password confirm is different to password.', 400);
                    return false;
                }
                var changeData = {
                    id : window._sys['user']['id'],
                    password : pwd,
                    password_confirmation : cpwd,
                };
                Api.Put('changeDefaultPassword', changeData, function(object, error){
                    if(object['status_code'] && object['message'] && object['status_code'] == 200 && object['message'] == 'OK'){
                        $.showSuccess('Change password successfully, relogin please.', 500, function(){
                            Api.set('_cache', false);
                            Api.set('access', false);
                            Api.set('token', false);
                            Api.set('user', false);
                            window.location.href = '/Public/login.html';
                        });
                    }else{
                        $.showError('Something error, retry later.', 400);
                    }
                });
                return false;
            });
        }
    }
    // add logout action listener
    $('#user-logout').click(function(){
        var logout = window.confirm('Are you sure to logout?');
        if(logout){
            Api.set('_cache', false);
            Api.set('access', false);
            Api.set('token', false);
            Api.set('user', false);
            $.showSuccess('Logout successfully, 3s turn to login page...', 400, function(){
                window.location.href = '/Public/login.html';
            }, 3000);
        }
        return false;
    });
    // 根据href初始化菜单的高亮效果（父菜单打开&子菜单高亮）
    var _path = window.location.href.split('#');
    _path = _path[0].split('/');
    _path[_path.length-1] = _path[_path.length-1].split('?')[0];
    _path = ['', _path[_path.length-2], _path[_path.length-1]];
    _path = _path.join('/');
    var pathFolder = {
        '/Category/add.html' : '/Category/index.html',
        '/Category/edit.html' : '/Category/index.html',
        '/Article/add.html' : '/Article/index.html',
        '/Article/edit.html' : '/Article/index.html',
        '/Users/add.html' : '/Users/index.html',
        '/Users/edit.html' : '/Users/index.html',
        '/Roles/add.html' : '/Roles/index.html',
        '/Roles/setAccess.html' : '/Roles/index.html',
        '/FaqCategory/add.html' : '/FaqCategory/index.html',
        '/FaqCategory/edit.html' : '/FaqCategory/index.html',
        '/Faq/edit.html' : '/Faq/index.html',
        '/Faq/add.html' : '/Faq/index.html',
        '/User/add.html' : '/User/index.html',
        '/User/edit.html' : '/User/index.html',
        '/Company/add.html' : '/Company/index.html',
        '/Company/edit.html' : '/Company/index.html',
    };
    if(pathFolder[_path]){
        _path = pathFolder[_path];
    }
    if($('.site-menu-item a[href="'+_path+'"]').parent().parent().hasClass('site-menu-sub')){
        $('.site-menu-item a[href="'+_path+'"]').parent().addClass('active');
        $('.site-menu-item a[href="'+_path+'"]').parent().parent().parent().addClass('open').addClass('active');
    }else{
        $('.site-menu-item a[href="'+_path+'"]').parent().addClass('active');
    }

    function Access(access){
    	this.access = access;
    	this.accessNodes = {
            // '/api/v1/auth/_' : true,
            // '/api/v1/auth/invalidate' : true,
            // '/api/v1/auth/login' : true,
            // '/api/v1/auth/refresh' : true,
            // '/api/v1/auth/user' : true,
            // '/api/v1/category/_' : true,
            // '/api/v1/category/add' : true,
            // '/api/v1/category/close' : true,
            // '/api/v1/category/delete' : true,
            // '/api/v1/category/detail' : true,
            // '/api/v1/category/edit' : true,
            // '/api/v1/category/listCategory' : true,
            // '/api/v1/category/open' : true,
            // '/api/v1/faq/_' : true,
            // '/api/v1/faq/__' : true,
            // '/api/v1/faq/add' : true,
            // '/api/v1/faq/close' : true,
            // '/api/v1/faq/delete' : true,
            // '/api/v1/faq/detail' : true,
            // '/api/v1/faq/edit' : true,
            // '/api/v1/faq/listFaq' : true,
            // '/api/v1/faq/open' : true,
            // '/api/v1/faqCate/_' : true,
            // '/api/v1/faqCate/add' : true,
            // '/api/v1/faqCate/close' : true,
            // '/api/v1/faqCate/delete' : true,
            // '/api/v1/faqCate/detail' : true,
            // '/api/v1/faqCate/edit' : true,
            // '/api/v1/faqCate/listCategory' : true,
            // '/api/v1/faqCate/open' : true,
            // '/api/v1/getNavigation' : true,
            // '/api/v1/news/_' : true,
            // '/api/v1/news/__' : true,
            // '/api/v1/news/add' : true,
            // '/api/v1/news/delete' : true,
            // '/api/v1/news/detail' : true,
            // '/api/v1/news/draft' : true,
            // '/api/v1/news/edit' : true,
            // '/api/v1/news/listNews' : true,
            // '/api/v1/news/publish' : true,
            // '/api/v1/rbac/_' : true,
            // '/api/v1/rbacNode/_' : true,
            // '/api/v1/rbacNode/add' : true,
            // '/api/v1/rbacNode/delete' : true,
            // '/api/v1/rbacNode/detail' : true,
            // '/api/v1/rbacNode/edit' : true,
            // '/api/v1/rbacNode/list' : true,
            // '/api/v1/rbacRole/access' : true,
            // '/api/v1/rbacRole/add' : true,
            // '/api/v1/rbacRole/add/_' : true,
            // '/api/v1/rbacRole/close' : true,
            // '/api/v1/rbacRole/delete' : true,
            // '/api/v1/rbacRole/detail' : true,
            // '/api/v1/rbacRole/list' : true,
            // '/api/v1/rbacRole/open' : true,
            // '/api/v1/rbacRole/setAccess' : true,
            // '/api/v1/rbacUser/add' : true,
            // '/api/v1/rbacUser/add/_' : true,
            // '/api/v1/rbacUser/close' : true,
            // '/api/v1/rbacUser/delete' : true,
            // '/api/v1/rbacUser/initPassword' : true,
            // '/api/v1/rbacUser/list' : true,
            // '/api/v1/rbacUser/modifyPass' : true,
            // '/api/v1/rbacUser/open' : true,
            // // #### other system apis
            // '/oth/er/feedback/list' : true,
            // '/oth/er/feedback/list' : true,
            // '/oth/er/settings/settings' : true,
            // '/oth/er/settings/site' : true,
            // '/other/v1/user/list' : true,
            // '/other/v1/company/list' : true,
            // '/other/v1/authtool/index' : true,
        };
        this.accessMenu = {};
    	// access data to node array
    	Access.prototype.findNodes = function(access){
    		for(var i=0; i<access.length; ++i){
    			if(access[i]['node_path']){
    				this.accessNodes[access[i]['node_path']] = true;
    			}
    			if(access[i]['_sub']){
    				this.findNodes(access[i]['_sub']);
    			}
    		}
    	}

    	this.findNodes(this.access);
        // console.log(this.access);
    	// console.log(this.accessNodes);
    	Access.prototype.showNodes = function(accessMenu){
            this.accessMenu = accessMenu;
            for(accessId in accessMenu){
                var _len = accessMenu[accessId].length, _access = false;
                for(var i=0; i<_len; ++i){
                    if(this.accessNodes[accessMenu[accessId][i]] === true){
                        _access = true;
                        break;
                    }
                }
                // console.log(accessId+'='+_access);
                if(_access){
                    $('#'+accessId).removeClass('__access');
                    $('.'+accessId).removeClass('__access');
                }
            }
    	}
        Access.prototype.isAccessToAccessId = function(accessId){
            if(this.accessMenu[accessId]){
                 var _len = this.accessMenu[accessId].length, _access = false;
                for(var i=0; i<_len; ++i){
                    if(this.accessNodes[this.accessMenu[accessId][i]] === true){
                        _access = true;
                        break;
                    }
                }
                return _access;
            }else{
                return false;
            }
               
        }
        // console.log(this.accessNodes['/api/v1/rbacRole/list'] === true);
    }
   
    window.Access = new Access(window._sys['access']);
    //加载权限列表
    $.ajax({
        url        : API_HOSTNAMES['admin']+'/api/v1/access/accessList',
        data       : {is_access:1},
        type       : "get",
        dataType   : 'json',
        beforeSend : function(XHR){},
        success : function(data){
            if (data['message'] && data['status_code'] && data['message'] == 'OK' && data['status_code'] == 200) {
                var accessHtml='';
                $.each(data['data'],function(k,v){
                   if($.isArray(v)) {
                       var tst = '';
                       for(var i=0;i<v.length;i++){
                          tst += '"'+v[i]+'",';
                       }
                       accessHtml+= '"'+k+'"' + ' : [' + tst.substring(0,tst.length-1) + '],';
                   } else {
                       accessHtml+='"'+k+'"' + ' : ["' + v + '"],';
                   }
                });
                var accessHtml = JSON.parse('{' + accessHtml.substring(0,accessHtml.length-1) + '}');
                window.Access.showNodes(accessHtml);
            } else {
                $.showError('Something Error, Retry Please.', 300, function () {});
            }
        }
    });


    /*window.Access.showNodes({
        // HTML Dom class or id : Api path
        '_access-users-parent' : ['/api/v1/data/listUser', '/api/v1/data/listCompany'],
        '_access-users-list' : ['/api/v1/data/listUser'],
        '_access-user-add' : ['/api/v1/data/addUser'],
        '_access-user-open' : ['/data-api/v1/user/updateStatus'],
        '_access-user-close' : ['/data-api/v1/user/updateStatus'],
        '_access-user-eidt' : ['/api/v1/data/userDetail'],
        '_access-company-list' : ['/api/v1/data/listCompany'],
        '_access-company-add' : ['/api/v1/data/addCompany'],
        '_access-company-edit-access' : ['/data-api/v1/company/detail'],
        '_access-authtool-parent' : ['/other/v1/authtool/index'],
        '_access-content-parent' : ['/api/v1/news/listNews', '/api/v1/category/listCategory'],
        '_access-article-category-list' : ['/api/v1/category/listCategory'],
        '_access-news-category-delete' : ['/api/v1/category/delete'],
        '_access-news-category-open' : ['/api/v1/category/open'],
        '_access-news-category-close' : ['/api/v1/category/close'],
        '_access-news-category-add' : ['/api/v1/category/add'],
        '_access-news-category-eidt' : ['/api/v1/category/detail'],
        '_access-article-list' : ['/api/v1/news/listNews'],
        '_access-news-delete' : ['/api/v1/news/delete'],
        '_access-news-open' : ['/api/v1/news/publish'],
        '_access-news-close' : ['/api/v1/news/draft'],
        '_access-news-add' : ['/api/v1/news/add'],
        '_access-news-eidt' : ['/api/v1/news/detail'],
        '_access-access-parent' : ['/api/v1/rbacNode/list', '/api/v1/rbacUser/list', '/api/v1/rbacRole/list'],
        '_access-access-node-list' : ['/api/v1/rbacNode/list'],
        '_access-create-top-node' : ['/api/v1/rbacNode/add'],
        '_access-edit-node' : ['/api/v1/rbacNode/edit'],
        '_access-delete-node' : ['/api/v1/rbacNode/delete'],
        '_access-access-user-list' : ['/api/v1/rbacUser/list'],
        '_access-rbac-user-add' : ['/api/v1/rbacUser/add'],
        '_access-rbac-user-init-password' : ['/api/v1/rbacUser/initPassword'],
        '_access-rbac-user-detail' : ['/api/v1/rbacUser/detail'],
        '_access-rbac-user-delete' : ['/api/v1/rbacUser/delete'],
        '_access-rbac-user-open' : ['/api/v1/rbacUser/open'],
        '_access-rbac-user-close' : ['/api/v1/rbacUser/close'],
        '_access-access-role-list' : ['/api/v1/rbacRole/list'],
        '_access-rbac-role-add' : ['/api/v1/rbacRole/add'],
        '_access-rbac-role-delete' : ['/api/v1/rbacRole/delete'],
        '_access-rbac-role-open' : ['/api/v1/rbacRole/open'],
        '_access-rbac-role-close' : ['/api/v1/rbacRole/close'],
        '_access-rbac-role-set-access' : ['/api/v1/rbacRole/setAccess'],
        '_access-faq-parent' : ['/oth/er/feedback/list', '/api/v1/faqCate/listCategory', '/api/v1/faq/listFaq'],
        '_access-faq-feedback-list' : ['/oth/er/feedback/list'],
        '_access-faq-category-list' : ['/api/v1/faqCate/listCategory'],
        '_access-faq-category-add' : ['/api/v1/faqCate/add'],
        '_access-faq-category-delete' : ['/api/v1/faqCate/delete'],
        '_access-faq-category-open' : ['/api/v1/faqCate/open'],
        '_access-faq-category-close' : ['/api/v1/faqCate/close'],
        '_access-faq-category-eidt' : ['/api/v1/faqCate/detail'],
        '_access-faq-list' : ['/api/v1/faq/listFaq'],
        '_access-faq-add' : ['/api/v1/faq/add'],
        '_access-faq-delete' : ['/api/v1/faq/delete'],
        '_access-faq-open' : ['/api/v1/faq/open'],
        '_access-faq-close' : ['/api/v1/faq/close'],
        '_access-faq-eidt' : ['/api/v1/faq/detail'],
        '_access-settings-parent' : ['/oth/er/settings/settings', '/oth/er/settings/site'],
        '_access-settings-settings' : ['/oth/er/settings/settings'],
        '_access-settings-site' : ['/oth/er/settings/site'],
    });*/
});
